//
//  TaskViewController.m
//  leo
//
//  Created by 常艳 on 15/9/19.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "TaskViewController.h"
#import "Task.h"
#import "common.h"
#import "ConfirmTaskTableViewCell.h"
#import "RecordTaskTableViewCell.h"
#import "AssignTaskViewController.h"
#import "GrowDataManager.h"
#import "User.h"
#import "Watch.h"
#import "DataManager.h"
#import "GrowManager.h"
#import "LeoMsg.h"
#import "Tooler.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width

@interface TaskViewController ()
@property(nonatomic,strong) NSArray *taskData;
@property(nonatomic,assign) BOOL isRegis;
@property(nonatomic,assign) float rate;
@property(nonatomic,strong) User *user;
@property(nonatomic,strong) Watch *selectWatch;
@property(nonatomic,strong) GrowDataManager *growDataManager;
@property(nonatomic,strong) GrowManager *growManager;
 @end

@implementation TaskViewController
@synthesize taskData;
@synthesize isRegis;
@synthesize rate;
@synthesize user;
@synthesize selectWatch;
@synthesize growDataManager;
@synthesize growManager;
-(void)dealloc
{
    [self removeObservers];
    taskData=NULL;
    user=NULL;
    selectWatch=NULL;
    growDataManager=NULL;
    growManager=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.


    self.extendedLayoutIncludesOpaqueBars=YES;
    self.title=@"任务";
    UIBarButtonItem *rightButton=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mission_choose_icon@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(assignTask)];
    [self.navigationItem setRightBarButtonItem:rightButton];
    rightButton=NULL;
    [self registerObservers];
    CGRect r=[ UIScreen mainScreen ].applicationFrame;
    rate=r.size.width/375;
    isRegis=NO;
    self.table.showsVerticalScrollIndicator=NO;
    self.table.backgroundColor=[UIColor colorWithRed:0.88 green:0.96 blue:1 alpha:1];
    [self.table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    growDataManager=[[GrowDataManager alloc] init];
    if(growDataManager==NULL)
        return;
    growManager=[[GrowManager alloc] init];
    if(growManager==NULL)
        return;
    //从数据库中读取任务列表
    user=[User sharedSingleton];
    if(user==NULL)
        return;
    DataManager *dataManager=[[DataManager alloc] init];
    if(dataManager==NULL)
        return;
    selectWatch=[dataManager getActiveWatch:user.uid];
    if(selectWatch==NULL)
        return;
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if(queue==NULL)
    {
        NSLog(@"%@,applicationWillEnterForeground,queue is null",DATAMANAGER_TAG);
        return;
    }
    dispatch_async(queue, ^{
        [growManager getHistoryTask:selectWatch.deviceUid randomCode:NULL completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if(result==SUCESS)
            {
                [self initData];
                [self.table reloadData];
            }
            else
            {
                //[Tooler showHttpToast:result description:description msg:@"获取任务失败" parentView:self.navigationController.view showPosition:TOAST_SHOW_MID hideAfterDelay:1];
            }
        }];
    });
    

   
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self initData];
    [self.table reloadData];
}
-(void)initData
{
    if(user==NULL)
        return;
    if(selectWatch==NULL)
        return;
    if(growDataManager==NULL)
        return;
    taskData=[growDataManager getTasks:user.uid targetUid:selectWatch.deviceUid];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(taskData!=NULL)
        return taskData.count;
    else
        return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row=[indexPath row];
    if(!self.isRegis)
    {
        [tableView registerNib:[UINib nibWithNibName:@"TaskTableViewCell" bundle:nil] forCellReuseIdentifier: @"taskcell"];
        [tableView registerNib:[UINib nibWithNibName:@"ConfirmTaskTableViewCell" bundle:nil] forCellReuseIdentifier:@"ConfirmTaskTableViewCell"];
        [tableView registerNib:[UINib nibWithNibName:@"RecordTaskTableViewCell" bundle:nil] forCellReuseIdentifier:@"RecordTaskTableViewCell"];
        self.isRegis=YES;
    }
    Task *task=[self.taskData objectAtIndex:row];
    if(task==NULL)
    {
        UITableViewCell *cell=[[UITableViewCell alloc] init];
        return cell;
    }
    UIImageView *bg=NULL;
    if(task.action==CONFIRM)
    {
        ConfirmTaskTableViewCell *cell = (ConfirmTaskTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ConfirmTaskTableViewCell"];
        cell.backgroundColor=[UIColor clearColor];
        cell.userInteractionEnabled=YES;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        bg=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"taskbg.png"]];
        cell.backgroundView=bg;
        cell.task=task;
        [cell initUI];
        NSLog(@"%ld", cell.descLable.numberOfLines)  ;
        return cell;
    }
    else if(task.action==RECORD)
    {
        RecordTaskTableViewCell *cell = (RecordTaskTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"RecordTaskTableViewCell"];
        cell.backgroundColor=[UIColor clearColor];
        cell.userInteractionEnabled=YES;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
     bg=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"taskbg.png"]];
        cell.backgroundView=bg;
        cell.task=task;
        cell.tb=self.table;
        [cell initUI];
        return cell;
    }
    else
    {
            TaskTableViewCell *cell = (TaskTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"taskcell"];
            cell.backgroundColor=[UIColor clearColor];
            cell.userInteractionEnabled=YES;
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            bg=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"taskbg.png"]];
            cell.backgroundView=bg;
            cell.task=task;

            [cell initUI];
            return cell;

    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row=[indexPath row];
    Task *task=[self.taskData objectAtIndex:row];
    if(task==NULL)
        return 110*self.rate;
    else
    {
        if(task.desc==NULL||[task.desc isEqualToString:@"(null)"]||[task.desc isEqualToString:@""])
            return 110*self.rate;
        else
        {
           
  
        if (task.action == CONFIRM) {
                
                CGFloat descHeight = [Tooler getHeightWithContent:task.desc width:WIDTH - 65 font:15];
                
                
                return 110 + descHeight - 18;
            }
            
         else if(task.action == RECORD)
         {
             CGFloat descHeight = [Tooler getHeightWithContent:task.desc width:WIDTH - 120 font:15];
             
             return 140  + descHeight - 18;
        }
            else
            {
                CGFloat descHeight = [Tooler getHeightWithContent:task.desc width:WIDTH - 65 font:15];
                
                return 134  + descHeight - 18;

            }
    }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}

-(void)assignTask
{
    AssignTaskViewController *assginTaskView=[[AssignTaskViewController alloc] init];
    [self.navigationController pushViewController:assginTaskView animated:YES];
}
-(void)registerObservers
{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:RECEIVEDPUSHTASK object:nil];
}
-(void)removeObservers
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:RECEIVEDPUSHTASK object:nil];
}
- (void)receiveNotification:(NSNotification *)sender {
    if([sender.name isEqualToString:RECEIVEDPUSHTASK])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self initData];
            [self.table reloadData];
        });
    }
  
}


@end
